package com.cgbl.cg.vm.mine

import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableField
import api.ShopServiceFactory
import com.alibaba.fastjson.JSON
import com.blankj.utilcode.util.NumberUtils
import com.cgbl.cg.utils.city.BeanTransferHelper
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.model.CollectDetailBean
import com.robot.base.model.CourseInfoBean
import com.robot.base.model.PageListBean
import com.robot.base.model.ShopCartBean
import com.robot.base.util.ToastUtils
import com.robot.base.util.arouter.ARouterUtil
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse
import java.util.ArrayList

class ShoppingCarViewModel(application: Application) : GLBaseViewModel(application) {

    var payPriceField = ObservableField("应付：￥0.00")
    var prudencePriceField = ObservableField("已省：￥0.00")

    val uc = UiChangeEvent()

    val deleteCartsCommand = BindingCommand<Any>(BindingAction {
        deleteCart()
    })

    val joinCollectionFolderCommand = BindingCommand<Any>(BindingAction {
        joinCollection()
    })

    val toBalanceCommand = BindingCommand<Any>(BindingAction {
        if (pickedGoods.isEmpty()) {
            ToastUtils.showShort("请选择购买商品!")
            return@BindingAction
        }
        ARouterUtil.goToActivityWithBundle(
            AppConstants.Router.Mine.A_MINE_CONFIRM_ORDER,
            Bundle().apply {
                putString(
                    AppConstants.BundleKey.SHOP_CART_BEAN, JSON.toJSONString(
                        BeanTransferHelper.cartsTransferConfirmOrderProduct(pickedGoods)
                    )
                )
            })
    })

    val pickedGoods = mutableListOf<ShopCartBean>()

    class UiChangeEvent {

        val cartData: SingleLiveEvent<List<ShopCartBean>> = SingleLiveEvent()

        val deleteSuccess: SingleLiveEvent<String> = SingleLiveEvent()

    }

    fun refreshCart() {
        val params = mapOf("pageNo" to 1, "pageSize" to 10)
        ShopServiceFactory.page(params).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<PageListBean<ShopCartBean>>>(this) {
            override fun onNext(t: BaseResponse<PageListBean<ShopCartBean>>) {
                uc.cartData.postValue(t.data.list)
            }
        })
    }

    fun balance(productList: List<ShopCartBean>) {
        pickedGoods.clear()
        pickedGoods.addAll(productList)
        var payPrice = 0.0//应付
        var oriPrice = 0.0//原价
        productList.forEach {
            payPrice += it.courseInfoDTO?.coursePrice?.toDouble() ?: 0.0
            oriPrice += it.courseInfoDTO?.rulingPrice?.toDouble() ?: 0.0
        }

        payPriceField.set("应付：￥${NumberUtils.format(payPrice, 2)}")
        prudencePriceField.set("已省：￥${NumberUtils.format(oriPrice - payPrice, 2)}")
    }

    private fun deleteCart() {
        val params = mapOf("ids" to pickedGoods.map { it.id })
        ShopServiceFactory.deletesCart(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {
                    ToastUtils.showShort("删除成功!")
                    uc.deleteSuccess.postValue("")
                    refreshCart()
                }
            })
    }

    private fun joinCollection() {
        val params = mapOf("ids" to "153,123")
        ShopServiceFactory.deletesCart(params)
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<Any>>(this) {
                override fun onNext(t: BaseResponse<Any>) {

                }
            })
    }
}